import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (!res.success) {
      return Promise.reject(new Error(res.message))
    } else {
      return res
    }
  },
  async error => {
    console.dir(error)
    if (error.response.status === 401) {
      // 清空信息,类似用户退出
      await store.dispatch('user/logout')
      router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
    }
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  }
  , error => {
    return Promise.reject(error)
  })

export default service
